﻿using System;
using System.Net;
using System.Net.Mail;
using System.Threading.Tasks;

public class EmailSender
{
    // 邮件服务器配置
    private readonly string _smtpServer;
    private readonly int _smtpPort;
    private readonly string _senderEmail;
    private readonly string _senderPassword;

    // 构造函数初始化邮件服务器信息
    public EmailSender(string smtpServer, int smtpPort, string senderEmail, string senderPassword)
    {
        _smtpServer = smtpServer;
        _smtpPort = smtpPort;
        _senderEmail = senderEmail;
        _senderPassword = senderPassword;
    }

    /// <summary>
    /// 发送带附件的邮件
    /// </summary>
    /// <param name="toEmail">收件人邮箱</param>
    /// <param name="subject">邮件主题</param>
    /// <param name="body">邮件内容</param>
    /// <param name="attachmentPaths">附件文件路径数组</param>
    /// <returns>是否发送成功</returns>
    public async Task<bool> SendEmailWithAttachmentsAsync(
        string toEmail,
        string subject,
        string body,
        string[] attachmentPaths = null)
    {
        try
        {
            // 创建邮件消息
            using (var mailMessage = new MailMessage())
            {
                mailMessage.From = new MailAddress(_senderEmail);
                mailMessage.To.Add(toEmail);
                mailMessage.Subject = subject;
                mailMessage.Body = body;
                mailMessage.IsBodyHtml = true; // 允许HTML格式内容

                // 添加附件
                if (attachmentPaths != null && attachmentPaths.Length > 0)
                {
                    foreach (var path in attachmentPaths)
                    {
                        if (!string.IsNullOrEmpty(path) && System.IO.File.Exists(path))
                        {
                            var attachment = new Attachment(path);
                            mailMessage.Attachments.Add(attachment);
                        }
                    }
                }

                // 配置SMTP客户端
                using (var smtpClient = new SmtpClient(_smtpServer, _smtpPort))
                {
                    smtpClient.Credentials = new NetworkCredential(_senderEmail, _senderPassword);
                    smtpClient.EnableSsl = true; // 启用SSL加密（大多数邮件服务器需要）

                    // 发送邮件
                    await smtpClient.SendMailAsync(mailMessage);
                }
            }

            return true;
        }
        catch (Exception ex)
        {
            Console.WriteLine($"发送邮件失败: {ex.Message}");
            return false;
        }
    }
}
